package com.wangzhen.bio.original;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 使用ServerSocket实现一个服务端程序，并且模拟HTTP协议响应http请求
 * 注意1：输出http响应的时候，如果不指定Content-Length响应头，那么浏览器请求的时候不能正常响应
 * 注意2：printWriter在结束的时候需要flush
 * 此为版本3，通过线程池的方式来接受用户请求
 */
public class ServerSocketDemoV3 {

    public static void main(String[] args) throws IOException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(8,
                8,
                1,
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(5000));

        ServerSocket serverSocket = new ServerSocket(9999);
        while (true) {
            Socket socket = serverSocket.accept();
            executor.execute(new RequestRunnable(socket));
        }
    }

    static class RequestRunnable implements Runnable {
        private Socket socket;
        public RequestRunnable(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            doRequest(socket);
        }
    }

    private static void doRequest(Socket socket) {
        System.out.println("开始处理客户端请求！");
        try (/*InputStream inputStream = socket.getInputStream();
             BufferedReader reader  = new BufferedReader(new InputStreamReader(inputStream));*/
             OutputStream outputStream = socket.getOutputStream();
             PrintWriter printWriter = new PrintWriter(outputStream)) {

            /*StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }*/

            String result = "{\"msg\": \"hello: \"}";
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Length:" + result.getBytes(StandardCharsets.UTF_8).length );
            printWriter.println("Content-Type:application/json");
            printWriter.println();
            printWriter.println(result);
            printWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
